package io.bdmc.modules.api.controller;
import javax.servlet.http.HttpServletRequest;



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;


public class BaseApiController{
    //public static final Logger logger = LoggerFactory.getLogger(getClass());
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    public HttpServletRequest request;

    /**
      * 从Request对象中获得客户端IP，处理了HTTP代理服务器和Nginx的反向代理截取了ip
      * @param request
      * @return ip
      */
      public  String getLocalIp() {
        String remoteAddr = request.getRemoteAddr();
        String forwarded = request.getHeader("X-Forwarded-For");
        String realIp = request.getHeader("X-Real-IP");

        String ip = null;
        if (realIp == null) {
            if (forwarded == null) {
                ip = remoteAddr;
            } else {
                ip = remoteAddr + "/" + forwarded.split(",")[0];
            }
        } else {
            if (realIp.equals(forwarded)) {
                ip = realIp;
            } else {
                if(forwarded != null){
                    forwarded = forwarded.split(",")[0];
                }
                ip = realIp + "/" + forwarded;
            }
        }
        return ip;
    }

    public String getLoginName(){
       String name =  request.getAttribute("loginName").toString();
       return name;
    }
}